﻿using DotNetOpenAuth.AspNet;
using Inovout.Account.Web.Models;
using Inovout.EntityPropertyValidation;
using Inovout.Memberships;
using Inovout.Memberships.Services;
using Inovout.Organizations.Memberships.Models;
using Inovout.Organizations.Memberships.Services;
using Inovout.Organizations.Models;
using Inovout.Security;
using Inovout.Services;
using Inovout.Web.Mvc;
using System.Web.Mvc;

namespace Inovout.Account.Web.Controllers
{
    public class OrganizationController : AccountController
    {
        public OrganizationController(IFormsAuthenticationService authenticateService,
            IOrganizationMembershipService organizationMembershipService,
            IMembershipUserService membershipUserService)
            : base(authenticateService, organizationMembershipService, membershipUserService)
        {
        }

        public ActionResult Bind(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            AuthenticationResult authenticationResult = (AuthenticationResult)TempData["AuthenticationResult"];

            var organizationSignUpInfo = new OrganizationSignUpInfo
            {
                OpenIdClaimedIdentifier = authenticationResult.ProviderUserId,
                OpenIdProvider = authenticationResult.Provider,
                OpenIdUserName = authenticationResult.UserName,
            };

            if (authenticationResult.ExtraData.ContainsKey("email"))
            {
                organizationSignUpInfo.OrganizationEmail = authenticationResult.ExtraData["email"].Trim();
            }

            TempData["AuthenticationResult"] = authenticationResult;
            return View("SignUp", organizationSignUpInfo);
        }

        public ActionResult Edit()
        {
            Inovout.Memberships.Models.Membership membership = base.Membership as Memberships.Models.Membership;
            IRepositoryService<OrganizationMembership> organizationService = ComponentRegistry.Resolve<IRepositoryService<OrganizationMembership>>();
            OrganizationMembership organizationMembership = organizationService.FindById(membership.Id);

            MembershipUserService membershipUserServiceService = Inovout.ComponentRegistry.Resolve<MembershipUserService>();
            Inovout.Memberships.IMembershipUser membershipUser = membershipUserServiceService.FindByMembership(membership);
            ViewBag.Email = ((SystemUser)membershipUser.SystemUser).FormsUserCredential[0].Email;
         
            string emailPropertyName = "Email";
            string type = membership.MembershipType.ToString();
            EntityPropertyValidationResult emailValidationResult = Inovout.ComponentRegistry.Resolve<IEntityPropertyValidationResultService>().FindByEntiry(membership, type, emailPropertyName);
            if (emailValidationResult != null)
            {
                ViewBag.IsEmailValid = emailValidationResult.IsValid;
            }
            return View(organizationMembership);
        }

        [HttpPost]
        public ActionResult Save(OrganizationMembership model, bool isEmailValid, string returnUrl)
        {           
            ViewBag.IsEmailValid = isEmailValid;
            ModelState.Remove("Mobile");
            if (ModelState.IsValid)
            {
                IRepositoryService<OrganizationMembership> organizationService = ComponentRegistry.Resolve<IRepositoryService<OrganizationMembership>>();
                IRepositoryService<OrganizationUnit> organizationUnitService = ComponentRegistry.Resolve<IRepositoryService<OrganizationUnit>>();
                model.Organization.Name = model.Name;
                model.Organization.Email = model.Email;

                organizationService.Save(model);
                return RedirectToAction("Message", new { messageType = MessageType.Success, message = Url.Encode("保存成功<a href='" + returnUrl + "'>继续</a>") });
            }
            return View("Edit", model);
        }
    }
}